package com.qiwo.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

public class FileUtil {

	static Logger log= LoggerFactory.getLogger(FileUtil.class);

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static void writeFile(String path, InputStream source)
			throws Exception
	{
		try
		{
			File f = new File(path);
			BufferedOutputStream bufferOut = new BufferedOutputStream(new FileOutputStream(f));
			byte[] b = new byte[10240];
			int j;
			while ((j = source.read(b)) > 0)
			{
				bufferOut.write(b, 0, j);
			}
			source.close();
			bufferOut.close();
		} catch (FileNotFoundException e) {
			log.error("写出文件的路径不正确:" + path);
			throw e;
		} catch (IOException e) {
			log.error("写出文件时发生错误:" + path);
			throw e;
		}
	}

	public static void writeFile(String path, byte[] data)
			throws Exception
	{
		try
		{
			File f = new File(path);
			BufferedOutputStream bufferOut = new BufferedOutputStream(new FileOutputStream(f));
			bufferOut.write(data);
			bufferOut.flush();
			bufferOut.close();
		} catch (FileNotFoundException e) {
			log.error("写出文件的路径不正确:" + path);
			throw e;
		} catch (IOException e) {
			log.error("写出文件时发生错误:" + path);
			throw e;
		}
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public static void delAllFile(String filePath)
	{
		delAllFile(new File(filePath));
	}

	public static void delAllFile(File file)
	{
		File[] fileList = file.listFiles();

		String dirPath = null;

		if (fileList != null) {
			for (int i = 0; i < fileList.length; i++)
			{
				if (fileList[i].isFile()) {
					fileList[i].delete();
				}

				if (!fileList[i].isDirectory())
					continue;
				dirPath = fileList[i].getPath();

				delAllFile(dirPath);
			}

		}

		file.delete();
	}

	public static void download(HttpServletResponse response, byte[] data, String fileName, String contentType)
			throws Exception
	{
		InputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(data));
		download(response, inputStream, fileName, contentType);
	}

	public static void download(HttpServletResponse response, File file, String fileName, String contentType)
			throws Exception
	{
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		download(response, inputStream, fileName == null ? file.getName() : fileName, contentType);
	}

	public static void download(HttpServletResponse response, InputStream inputStream, String fileName, String contentType)
			throws Exception
	{
		if (StringUtils.isNotBlank(contentType))
			response.setContentType(contentType);
		else {
			response.setContentType("application/octet-stream");
		}
		fileName = StringUtils.isNotBlank(fileName) ? "unknow_file" : fileName;
		response.setHeader("Content-Disposition",
				"attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1"));
		response.setContentLength(inputStream.available());
		InputStream bis = new BufferedInputStream(inputStream);
		byte[] b = new byte[1024];

		OutputStream out = response.getOutputStream();
		int j;
		while ((j = bis.read(b)) > 0)
		{
			out.write(b, 0, j);
		}
		bis.close();
		out.flush();
		out.close();
	}

	public static void download(HttpServletResponse response, String filePath, String fileName, String type)
			throws Exception
	{
		File file = new File(filePath);
		if (!file.exists())
			throw new IOException("该文件不存在，或已被删除！");
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		download(response, inputStream,
				StringUtils.isNotBlank(fileName) ? fileName : filePath.substring(filePath.lastIndexOf("/") + 1), type);
	}

	public static void download(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName, String type)
			throws Exception
	{
		File file = new File(filePath);
		if (!file.exists())
			throw new IOException("该文件不存在，或已被删除！");
		InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
		download(response, inputStream,
				StringUtils.isNotBlank(fileName) ? fileName : filePath.substring(filePath.lastIndexOf("/") + 1), type);
	}
}
